import os
import sys
import tempfile
import shutil
import logging
import subprocess

from video_processor import VideoProcessor
from audio_processor import AudioProcessor
from metadata_handler import MetadataHandler
from config import config
from utils import setup_logger

# 设置日志
logger = setup_logger()

def run_command(command):
    """运行系统命令并返回结果"""
    try:
        result = subprocess.run(command, shell=True, check=True,
                              stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        return result.stdout
    except subprocess.CalledProcessError as e:
        logger.error(f"命令执行失败: {e.stderr}")
        raise

# 将run_command函数注入到metadata_handler模块
import metadata_handler
metadata_handler.run_command = run_command

def process_video_file(input_file, output_file, progress_callback=None):
    """处理视频文件的主流程"""
    temp_dir = None
    try:
        # 创建临时目录
        temp_dir = tempfile.mkdtemp(prefix="video_dedup_")
        logger.info(f"创建临时目录: {temp_dir}")

        # 处理视频
        video_processor = VideoProcessor()
        video_temp = os.path.join(temp_dir, "video_temp.mp4")
        video_processor.process_video(input_file, video_temp, progress_callback)

        # 处理音频
        audio_processor = AudioProcessor()
        audio_temp = os.path.join(temp_dir, "audio_temp.wav")
        audio_processor.process_audio(input_file, audio_temp)

        # 合并视频和音频
        metadata_handler = MetadataHandler()
        final_temp = os.path.join(temp_dir, "final_temp.mp4")
        metadata_handler.merge_video_audio(video_temp, audio_temp, final_temp)

        # 修改元数据
        metadata_handler.modify_video_metadata(final_temp, output_path=output_file)

        logger.info(f"处理完成: {output_file}")

    except Exception as e:
        logger.error(f"处理失败: {str(e)}")
        raise
    finally:
        # 清理临时文件
        if temp_dir and os.path.exists(temp_dir):
            shutil.rmtree(temp_dir)
            logger.info(f"清理临时目录: {temp_dir}")

def main():
    """主函数"""
    input_path = "input.mp4"  # 默认输入文件
    output_path = "output.mp4"  # 默认输出文件

    if len(sys.argv) > 1:
        input_path = sys.argv[1]
    if len(sys.argv) > 2:
        output_path = sys.argv[2]

    process_video_file(input_path, output_path)

if __name__ == "__main__":
    main()
